// pages/usercenter/index.js
const app = getApp()
const fetch = require('../../utils/fetch')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLogin:false,
    userInfo:null,
    unReadNotice:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var isLogin = app.isLogin();
    // TODO:test
    // isLogin = true;
    console.log(isLogin);
    var that = this;
    if (isLogin) {
      app.getUserInfo(
        function (res) {
          console.log(res, "onLoad");
          console.log(isLogin);
          that.setData({
            userInfo: res,
            isLogin: isLogin
          });
        }
      );
      that.getUnreadNoticeNum();
    }else {
      this.setData({
        isLogin: false,
        userInfo: null,
        unReadNotice: '',
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  toLogin:function(){
    if(!this.data.isLogin){
      wx.navigateTo({
        url: '../login/index',
      })
    }
  },
  exit:function(){
    var that = this;
    wx.showModal({
      title: '退出提示',
      content: '确定要退出当前账号么？',
      success: function (res) {
        if (res.confirm) {
            
            wx.showLoading({
              title: '退出账号中...',
            });
            app.toLoginOut();
            setTimeout(function(){
              wx.hideLoading();
              that.setData({
                isLogin:false,
                userInfo:null
              });
            },1000);

        }
      }
    })
  },

  toSubsidy:function(){
    if (this.data.isLogin) {
      wx.navigateTo({
        url: '../subsidy/index',
      })
    }
  },
  toNotice: function () {
    if (this.data.isLogin) {
      wx.navigateTo({
        url: '../notice/index',
      })
    }
  },
  toFeedback: function () {
   
      wx.navigateTo({
        url: '../report/index',
      })
    
  },

  getUnreadNoticeNum:function(){
    var that = this;
    fetch('yggc/commonApi/getUnReadNoticeNum', { "idcard": app.globalData.idcard},'POST').then  (function (result) {
      console.log(result);
      var code = result.data.code;
      if (code == 200) {
        var num = result.data.data.num;
        var desc = '';
        if (num){
           desc =  num >= 100 ?"99+":num;
        }
        that.setData({
          unReadNotice: desc
        });
      }
    });
  }
})